/**
 * Copyright (c) 2012-2013 Nokia Corporation. All rights reserved. Nokia and
 * Nokia Connecting People are registered trademarks of Nokia Corporation.
 * Oracle and Java are trademarks or registered trademarks of Oracle and/or its
 * affiliates. Other product and company names mentioned herein may be
 * trademarks or trade names of their respective owners. See LICENSE.TXT for
 * license information.
 */
package com.nokia.example.fuelcalculator.view;

import com.nokia.example.fuelcalculator.Midlet;
import com.nokia.example.fuelcalculator.utils.Commands;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;

/**
 * The class that manages the views, showing them, and handling all the
 * navigational commands.
 */
public class ViewManager
    implements CommandListener {

    private Display display;
    private View totalConsumptionView;
    private View addFillingView;
    private View helpView;
    private View aboutView;
    private boolean returnToAddFilling;

    /**
     * Constructor
     *
     * @param display
     */
    public ViewManager(Display display) {
        this.display = display;
        this.totalConsumptionView = new TotalConsumptionView(this);
        this.addFillingView = new AddFillingView(this);
        this.aboutView = new AboutView(this);
        this.helpView = new HelpView(this);
    }

    /**
     * Shows the entrance view after splash screen.
     */
    public void showEnterView() {
        updateAndShowView(totalConsumptionView);
        returnToAddFilling = false;
    }

    /**
     * Shows an alert.
     *
     * @param alert
     * @param returnPoint
     */
    public void showAlert(Alert alert, View returnPoint) {
        display.setCurrent(alert, returnPoint.getDisplayable());
    }

    /**
     * @see javax.microedition.lcdui.CommandListener#commandAction(Command,
     * Displayable)
     */
    public void commandAction(Command c, Displayable d) {
        if (c == Commands.BACK_FROM_ABOUT_OR_HELP) {
            if (returnToAddFilling) {
                showView(addFillingView);
            } else {
                showEnterView();
            }
        } else if (c == Commands.BACK_FROM_ADD_FILLING) {
            showEnterView();
        } else if (c == Commands.GOTO_ABOUT_VIEW) {
            showView(aboutView);
        } else if (c == Commands.GOTO_HELP_VIEW) {
            showView(helpView);
        } else if (c == Commands.GOTO_ADD_FILLING_VIEW) {
            updateAndShowView(addFillingView);
            returnToAddFilling = true;
        } else if (c == Commands.EXIT) {
            Midlet.getInstance().destroyApp(true);
        }
    }

    private void updateAndShowView(View next) {
        next.updateUI();
        showView(next);
    }

    private void showView(View next) {
        display.setCurrent(next.getDisplayable());
    }
}
